<template>
  <el-card shadow="never">
    <el-form label-width="auto" :inline="true" size="small">
      <el-row>
        <el-col :span="6">
          <el-form-item label="合同编号" style="width: 85%">
            <el-input
              v-model="searchForm.contractNo"
              placeholder="请输入 合同编号"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="合同名称" style="width: 85%">
            <el-select
              v-model="searchForm.contractName"
              clearable
              filterable
              remote
              remote-show-suffix
              placeholder="请选择 合同名称"
              :remote-method="getContractNameList"
              size="small"
            >
              <el-option
                v-for="item in contractOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                class="!w-[500px]"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="采购单位" style="width: 85%">
            <el-input
              v-model="searchForm.purchaseDeptName"
              placeholder="请输入 采购单位"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="项目名称" style="width: 85%">
            <el-select
              v-model="searchForm.projectName"
              clearable
              filterable
              remote
              remote-show-suffix
              placeholder="请选择 项目名称"
              :remote-method="getProjectNameList"
              size="small"
            >
              <el-option
                v-for="item in projectOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                class="!w-[500px]"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="开票时间" style="width: 85%">
            <el-date-picker
              v-model="searchForm.invoicingDate"
              type="daterange"
              range-separator="-"
              start-placeholder="开始"
              end-placeholder="结束"
              value-format="YYYY-MM-DD"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="发票金额" style="width: 85%">
            <el-input
              v-model="searchForm.invoicingPrice"
              placeholder="请输入 发票金额"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="关联发票" style="width: 85%">
            <el-select
              v-model="searchForm.invoiceBindStatus"
              placeholder="请选择 关联发票"
              size="small"
              clearable
            >
              <el-option
                v-for="item in invoiceBindStatusOptions"
                :key="item.label"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="发票状态" style="width: 85%">
            <el-select
              v-model="searchForm.statusList"
              placeholder="请选择 发票状态"
              size="small"
              clearable
            >
              <el-option
                v-for="item in statusListOptions"
                :key="item.label"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24" style="text-align: right">
          <el-button
            color="#1E3485"
            size="small"
            icon="Download"
            @click="getList(true)"
          >导出</el-button
          >
          <el-button
            color="#1E3485"
            size="small"
            :icon="Edit"
            @click="
              toDetail(
                { title: '新建项目发票', action: 'add' },
                'addPjctInvoice'
              )
            "
            >新建</el-button
          >
          <el-button
            color="#1E3485"
            size="small"
            :icon="Search"
            @click="
              tablePage.currentPage = 1;
              getList();
            "
            >搜索</el-button
          >
          <el-button
            type="default"
            size="small"
            :icon="Delete"
            @click="clearAllFields()"
            >清空</el-button
          >
        </el-col>
      </el-row>
    </el-form>
    <vxe-table
      border
      min-height="300"
      max-height="650"
      header-align="center"
      :column-config="{ resizable: true }"
      :row-config="{ isHover: true }"
      :data="tableData"
      size="mini"
      :loading="tableLoading"
      :pager-config="tablePage"
      style="margin-top: 1%"
    >
      <vxe-column
        type="seq"
        title="序号"
        width="50"
        fixed="left"
        align="center"
      />
      <vxe-column
        v-for="column in tableColumns"
        :key="column.field"
        header-align="center"
        :field="column.field"
        :title="column.title"
        :min-width="column.width"
        :align="column.align"
        show-overflow
      >
        <template
          v-if="column.field === 'invoiceType'"
          v-slot:default="{ row }"
        >
          <span v-if="row.invoiceType == '0'">电子发票（增值税专用发票）</span>
          <span v-if="row.invoiceType == '1'">增值税电子专用发票</span>
          <span v-if="row.invoiceType == '2'">增值税专用发票</span>
        </template>
        <template
          v-else-if="column.field === 'invoiceSource'"
          v-slot:default="{ row }"
        >
          <span v-if="row.invoiceSource == '0'">对账单</span>
          <span v-if="row.invoiceSource == '1'">结算单</span>
          <span v-if="row.invoiceSource == '2'">项目订单</span>
        </template>
        <template
          v-else-if="column.field === 'invoiceBindStatus'"
          v-slot:default="{ row }"
        >
          <span v-if="row.invoiceBindStatus == '0'">未绑定</span>
          <span v-if="row.invoiceBindStatus == '1'">已绑定</span>
        </template>
        <template
          v-else-if="column.field === 'statusList'"
          v-slot:default="{ row }"
        >
          <span v-if="row.status == '0'">未申请</span>
          <span v-if="row.status == '1'">未申请</span>
          <span v-if="row.status == '2'">未申请</span>
          <span v-if="row.status == '3'">开票中</span>
          <span v-if="row.status == '4'">开票中</span>
          <span v-if="row.status == '5'">已开票</span>
          <span v-if="row.status == '6'">已开票</span>
          <span v-if="row.status == '7'">已开票</span>
          <span v-if="row.status == '8'">已开票</span>
        </template>
        <template
          v-else-if="column.field === 'invoicingStatus'"
          v-slot:default="{ row }"
        >
          <span v-if="row.invoicingStatus == '0'">正常</span>
          <span v-if="row.invoicingStatus == '1'">作废</span>
          <span v-if="row.invoicingStatus == '2'">红冲</span>
        </template>
        <template
          v-else-if="column.field === 'status'"
          v-slot:default="{ row }"
        >
          <span v-if="row.status == '0'">待申请</span>
          <span v-if="row.status == '1'">待云采确认</span>
          <span v-if="row.status == '2'">核实驳回</span>
          <span v-if="row.status == '3'">待开票</span>
          <span v-if="row.status == '4'">开票中</span>
          <span v-if="row.status == '5'">开票失败</span>
          <span v-if="row.status == '6'">开票完成</span>
          <span v-if="row.status == '7'">已作废</span>
          <span v-if="row.status == '8'">红冲</span>
        </template>
        <template
          v-else-if="column.field === 'overdue'"
          v-slot:default="{ row }"
        >
          <span v-if="row.expectPaymentNum >= 0 && row.expectPaymentNum">{{
            "剩余" + row.expectPaymentNum + "天"
          }}</span>
          <span v-if="row.expectPaymentNum < 0 && row.expectPaymentNum">{{
            "已逾期" + Math.abs(row.expectPaymentNum) + "天"
          }}</span>
        </template>
        <template v-else v-slot:default="{ row }">
          {{ row[column.field] }}
        </template>
      </vxe-column>
      <vxe-column title="操作" min-width="200" align="center" fixed="right">
        <template v-slot:default="{ row }">
          <vxe-button
            type="text"
            @click="toDetail({ id: row.id, action: 'view' }, 'viewPjctInvoice')"
            >查看</vxe-button
          >
          <vxe-button
            v-if="[0, 2].includes(row.status)"
            type="text"
            @click="toDetail({ id: row.id, action: 'edit' }, 'editPjctInvoice')"
            >编辑</vxe-button
          >
          <vxe-button
            v-if="[0, 2].includes(row.status)"
            type="text"
            @click="rowDelete(row)"
            >删除</vxe-button
          >
          <vxe-button
            v-if="row.status == 0"
            type="text"
            @click="submitInvoice(row)"
            >提交</vxe-button
          >
          <vxe-button
            v-if="row.status == 3"
            type="text"
            @click="toDetail({ id: row.id, action: 'invo' }, 'invoPjctInvoice')"
            >开票</vxe-button
          >
          <vxe-button
            v-if="row.status == 8"
            type="text"
            @click="
              toDetail({ id: row.id, action: 'reInvo' }, 'reInvoPjctInvoice')
            "
            >重新生成</vxe-button
          >
          <vxe-button
            v-if="row.status == 1"
            type="text"
            @click="
              toDetail({ id: row.id, action: 'exaime' }, 'exaimePjctInvoice')
            "
            >云采确认</vxe-button
          >
          <!-- 结算单发票 -->
          <vxe-button
            v-if="row.status == 6"
            type="text"
            @click="showSubInvoiceDialog(row)"
            >关联发票</vxe-button
          >
          <!-- 项目订单发票 且 无结算单 ？ -->
          <vxe-button
            v-if="row.invoiceSource == '2' && row.status == 6"
            type="text"
            @click="showSettlementDialog(row)"
            >关联结算单</vxe-button
          >
          <vxe-button
            v-if="row.status == 6"
            type="text"
            @click="redPushInvoiceInfo(row)"
            >红冲</vxe-button
          >
        </template>
      </vxe-column>
    </vxe-table>
    <vxe-pager
      v-model:current-page="tablePage.currentPage"
      v-model:page-size="tablePage.pageSize"
      :layouts="[
        'Sizes',
        'PrevJump',
        'PrevPage',
        'Number',
        'NextPage',
        'NextJump',
        'FullJump',
        'Total'
      ]"
      :total="tablePage.total"
      size="mini"
      style="margin-top: 2%"
      @page-change="handlePageChange"
    />
    <div class="dialogs">
      <subInvoiceSelectDialog
        :id="subInvoiceId"
        :data="invoicedata"
        :visible="subInvoiceDialogVisible"
        @close="closeSubInvoiceDialog"
      />
      <settlementSelectDialog
        :id="settlementId"
        :visible="settlementDialogVisible"
        :bindType="'inList'"
        @close="closeSettlementDialog"
      />
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { Delete, Search, Edit } from "@element-plus/icons-vue";
import { VxePagerEvents } from "vxe-table";
import { ElMessage, ElMessageBox } from "element-plus";
import subInvoiceSelectDialog from "./components/dialog/subInvoiceSelectDialog.vue";
import settlementSelectDialog from "./components/dialog/PjctSettlementSelectDialog.vue";
import { useDetail } from "@/views/ERP_InvoiceManage/ERP_Projectinvoice/components/utils/hooks";
import { getSalesContractsList } from "@/api/ERP_sales";
import { getProjectList } from "@/api/ERP_public";
import {
  getSoInvoiceList,
  submitInvoiceInfo,
  redPushInvoice,
  delProjectInvoiceData
} from "@/api/ERP_InvoiceManage";
import {http} from "@/utils/http";
import {baseUrlApi} from "@/store/utils";

///////////////////////// 数据准备 /////////////////////////
// 路由跳转
const { toDetail, router } = useDetail();
// 搜索表单
let searchForm = reactive({
  contractNo: "",
  contractName: "",
  purchaseDeptName: "",
  projectName: "",
  invoicingPrice: "",
  invoiceBindStatus: "",
  statusList: "",
  invoicingDate: []
});
// 清空按钮点击事件
const clearAllFields = () => {
  for (const key in searchForm) {
    if (searchForm.hasOwnProperty(key)) {
      if (key === "invoicingDate") {
        searchForm[key] = [];
      } else {
        searchForm[key] = "";
      }
    }
  }
};
// 合同名称选择
let contractOptions = ref([]);
// 合同名称列表下拉框
const getContractNameList = (query: string) => {
  getSalesContractsList({
    pageIndex: 1,
    pageSize: 10,
    contractType: "0",
    contractName: query
  }).then(response => {
    contractOptions.value = (response as any).data.records.map(item => ({
      label: item.contractName,
      value: item.contractName
    }));
  });
  if (query) {
    setTimeout(() => {
      getSalesContractsList;
    }, 1500);
  }
};
// 项目名称选择
let projectOptions = ref([]);
// 项目名称列表下拉框
const getProjectNameList = (query: string) => {
  getProjectList({
    pageIndex: 1,
    pageSize: 10,
    projectName: query
  }).then(response => {
    projectOptions.value = (response as any).data.records.map(item => ({
      label: item.projectName,
      value: item.projectName
    }));
  });
  if (query) {
    setTimeout(() => {
      getProjectList;
    }, 1500);
  }
};
// 关联发票字典
let invoiceBindStatusOptions = ref([
  { label: "未关联", value: "0" },
  { label: "已关联", value: "1" }
]);
// 发票状态字典
let statusListOptions = ref([
  { label: "未申请", value: "0, 1, 2" },
  { label: "开票中", value: "3, 4" },
  { label: "已开票", value: "5, 6, 7, 8" }
]);
///////////////////////// 数据展示 /////////////////////////
// 表格数据
let tableData = ref([]);
let tableLoading = ref(false);
// 表格列
const tableColumns = ref([
  {
    field: "contractNo",
    title: "合同编号",
    width: 150,
    align: "left"
  },
  {
    field: "contractName",
    title: "合同名称",
    width: 200,
    align: "left"
  },
  {
    field: "projectName",
    title: "项目名称",
    width: 200,
    align: "left"
  },
  {
    field: "invoiceType",
    title: "发票类型",
    width: 150,
    align: "center"
  },
  {
    field: "invoiceHeader",
    title: "发票抬头",
    width: 200,
    align: "left"
  },
  {
    field: "invoicingPrice",
    title: "发票金额（元）",
    width: 120,
    align: "right"
  },
  {
    field: "overdue",
    title: "逾期情况",
    width: 120,
    align: "right"
  },
  {
    field: "invoiceSource",
    title: "发票来源",
    width: 120,
    align: "center"
  },
  {
    field: "invoiceBindStatus",
    title: "关联发票",
    width: 120,
    align: "center"
  },
  {
    field: "applyName",
    title: "申请人",
    width: 120,
    align: "center"
  },
  {
    field: "applyDate",
    title: "申请时间",
    width: 120,
    align: "center"
  },
  {
    field: "statusList",
    title: "发票状态",
    width: 120,
    align: "center"
  },
  {
    field: "invoicingStatus",
    title: "开票状态",
    width: 120,
    align: "center"
  },
  {
    field: "status",
    title: "数据状态",
    width: 120,
    align: "center"
  }
]);
// 表格分页配置
let tablePage = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 15
});
// 表格分页事件
const handlePageChange: VxePagerEvents.PageChange = ({
  currentPage,
  pageSize
}) => {
  tablePage.currentPage = currentPage;
  tablePage.pageSize = pageSize;
  getList();
};
///////////////////////// 弹窗类 /////////////////////////
// 关联发票弹窗
let subInvoiceDialogVisible = ref(false);
let subInvoiceId = ref("");
let invoicedata = ref("");
function showSubInvoiceDialog(row) {
  subInvoiceId.value = row.contractId;
  invoicedata.value = row;
  subInvoiceDialogVisible.value = true;
}
function closeSubInvoiceDialog(val: boolean) {
  subInvoiceDialogVisible.value = val;
  getList();
}
// 关联结算单弹窗
let settlementDialogVisible = ref(false);
let settlementId = ref("");
function showSettlementDialog(row) {
  settlementId.value = row.id;
  settlementDialogVisible.value = true;
}
function closeSettlementDialog(val: boolean) {
  settlementDialogVisible.value = val;
  getList();
}
///////////////////////// 数据请求 /////////////////////////
// 获取列表
async function getList(isExport) {
  let params: ApiParams = {};

  if (searchForm.contractNo) params.contractNo = searchForm.contractNo;
  if (searchForm.contractName) params.contractName = searchForm.contractName;
  if (searchForm.purchaseDeptName)
    params.purchaseDeptName = searchForm.purchaseDeptName;
  if (searchForm.projectName) params.projectName = searchForm.projectName;
  if (searchForm.invoicingPrice)
    params.invoicingPrice = searchForm.invoicingPrice;
  if (searchForm.invoiceBindStatus)
    params.invoiceBindStatus = searchForm.invoiceBindStatus;
  if (searchForm.statusList) params.statusList = searchForm.statusList;
  if (searchForm.invoicingDate) {
    params.beginDate = searchForm.invoicingDate[0];
    params.endDate = searchForm.invoicingDate[1];
  }
  if(isExport) {
    await http.request('get',baseUrlApi("soinvoice/export/file"), {params})
    return
  }
  params.pageIndex = tablePage.currentPage;
  params.pageSize = tablePage.pageSize;
  tableLoading.value = true;
  try {
    const response: ApiResponse = await getSoInvoiceList(params);
    tableData.value = response.data.records;
    tablePage.total = response.data.totalElements;
  } catch (error) {
    ElMessage.error("获取列表失败");
  } finally {
    tableLoading.value = false;
  }
}
// 删除按钮
async function rowDelete(row) {
  ElMessageBox.confirm("确认删除该发票吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      let params: ApiParams = {};
      params.id = row.id;
      const response: ApiResponse = await delProjectInvoiceData(params);
      if (response.code === 200) {
        ElMessage.success("删除成功");
        getList();
      } else {
        ElMessage.error("删除失败: " + response.msg);
      }
    })
    .catch(() => {
      ElMessage.error("已取消");
    });
}
// 提交开票信息
async function submitInvoice(row) {
  ElMessageBox.confirm("是否提交开票申请?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    let params: ApiParams = {};
    params.id = row.id;
    try {
      const response: ApiResponse = await submitInvoiceInfo(params);
      if (response.code === 200) {
        ElMessage.success("提交成功");
        getList();
      } else {
        ElMessage.error("提交失败: " + response.msg);
      }
    } catch (error) {}
  });
}
// 红冲
async function redPushInvoiceInfo(row) {
  ElMessageBox.confirm("是否开具红冲发票?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    let params: ApiParams = {};
    params.id = row.id;
    try {
      const response: ApiResponse = await redPushInvoice(params);
      if (response.code === 200) {
        ElMessage.success("红冲成功");
        getList();
      } else {
        ElMessage.error("红冲失败: " + response.msg);
      }
    } catch (error) {}
  });
}
///////////////////////// 公共 /////////////////////////
// 初始化
onMounted(async () => {
  getList();
});
</script>

<style lang="scss" scoped></style>
